package com.frontop.terminal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.entity.Message;
import com.frontop.terminal.entity.Program;
import com.frontop.terminal.model.bo.TerminalResourceBO;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.service.ICommandSerivce;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.WriteDataUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 修改互动程序名称
 * </p>
 *
 * @author Frontop
 * @since :2022-06-29
 **/
public class ProgramUpdateNameServiceImpl implements ICommandSerivce {
    /**
     * 执行业务
     *
     * @param message 消息对象
     * @return T
     */
    @SuppressWarnings("ConstantConditions")
    @Override
    public RestResult executeWork(Message message) {
        Map<String, Program> programMap = ReadDataUtil.getProgramListMap();
        if (ObjectUtil.isNull(programMap) && programMap.isEmpty()) {
            return RestResult.failed("程序列表为空");
        }

        TerminalResourceBO resourceBO = JSON.parseObject(message.getCommand(), TerminalResourceBO.class);

        if (ObjectUtil.isNotNull(resourceBO) && programMap.containsKey(resourceBO.getId())) {

            Program program = programMap.get(resourceBO.getId());
            program.setName(resourceBO.getResourceName());
            List<Program> programList = new ArrayList<>(programMap.values());
            //save
            WriteDataUtil.write(programList, ReadDataUtil.PROGRAM_LIST_CODING);
        }

        return RestResult.success();
    }
}
